#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   dns_rndc_local.sh
# Version:    1.0
# Date:       2013/10/16
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    02系统基本功能-04网络服务-06DNS-01字符模式-05使用rndc控制DNS服务-01使用rndc控制本地DNS服务
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/10/25
#             - Start named service, rndc control local dns service
# ----------------------------------------------------------------------

##! @TODO: start named service
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_setup()
{
    serv=named
    CONF="/etc/named.conf"

    # backup /etc/named.conf
    cp ${CONF} ${CONF}.bak
    EchoResult "backup ${CONF}"

    # check owner of /etc/named.conf
    OWNER=`ls -l ${CONF} | awk '{print $3,$4}'`
    if [ "${OWNER}" != "named named" ]; then
        chown named:named ${CONF}
        EchoResult "check owner of ${CONF}"
    fi


    trap do_cleanup INT EXIT
}


##! @TODO:  test rndc on local
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function do_test1()
{
    #rndc-confgen
    RNDCCONF="/etc/rndc.conf"
    [ -f ${RNDCCONF} ] && rm -f ${RNDCCONF}

    rndc-confgen > ${RNDCCONF}

    # update rndc.key
    RNDCKEY="/etc/rndc.key"
    mv ${RNDCKEY} ${RNDCKEY}.bak
    grep -E "^# key" -A 8 ${RNDCCONF} > ${RNDCKEY}

    sed -i 's/^# //g' ${RNDCKEY}

    # check owner of /etc/named.conf
    OWNER=`ls -l ${RNDCKEY} | awk '{print $3,$4}'`
    if [ "${OWNER}" != "named named" ]; then
        chown named:named ${RNDCKEY}
        EchoResult "check owner of ${RNDCKEY}"
    fi


    # add include /etc/rndc.key in named.conf
    echo "include \"${RNDCKEY}\";" >> ${CONF}

    # restart dns service
    restart_daemon ${serv}

    sleep 3
    # check named start, local
    status_daemon ${serv} && netstat -nlutp | grep ${serv}
    EchoResult "service ${serv} start"


    ########################
    # rndc
    rndc status

    rndc querylog on
    # check log messages
    PID_NAMED=`pidof ${serv}`
    grep "named\[${PID_NAMED}\]: query logging is now on" /var/log/messages
    EchoResult "rndc querylog on"

    # rndc stop
    rndc stop

    sleep 3
    grep "named\[${PID_NAMED}\]: exiting" /var/log/messages
    EchoResult "rndc stop"

}

##! @TODO:  cleanup tmp files, back up named.conf and stop named service.
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function do_cleanup()
{
    stop_daemon service ${serv}
    [ -f ${CONF}.bak ] && mv -f ${CONF}.bak ${CONF}
    rm -f ${RNDCCONF}
    [ -f ${RNDCKEY}.bak ] && mv -f ${RNDCKEY}.bak ${RNDCKEY}

}
# include lib files

if [ -z "$SFROOT" ]
then
    CMDLIB=./
    SFROOT=./
else
    CMDLIB=${SFROOT}/testcases/Network_Service
fi

. ${SFROOT}/lib/Echo.sh
. ${CMDLIB}/lib/Net.sh
do_setup

do_test1
EchoResult "rndc local dns service"
echo ""
